package com.abocode.aichat.core.application;
import com.abocode.aichat.core.interfaces.constant.ConfigHolder;
import com.abocode.aichat.data.*;
import com.abocode.aichat.server.context.channel.ChannelWrapper;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.context.pipeline.MessagePersistencePipeline;
import com.abocode.aichat.server.modules.ModuleServiceHandler;
import com.abocode.aichat.server.context.delivery.reply.Replies;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author guanxf
 */
@Service
public class ChatMessageHandler implements ModuleServiceHandler {
    @Autowired
    private MessagePersistencePipeline messagePersistencePipeline;
    @Override
    public Replies execute(ChannelWrapper channelWrapper, MessageStanza stanza, ServerRuntimeContext serverRuntimeContext) {
        Channel fromChannel = channelWrapper.getChannel();
        ReqMessageBody body = JSON.parseObject(stanza.body().toString(),ReqMessageBody.class);
        String toJid =body.getTo();
        Replies replies = new Replies();
        //判断用户是否是黑名单
        Entity toEntity;
        try {
             toEntity = EntityImpl.parse(toJid);
        }catch (Exception e){
            replies.addReply(fromChannel, StanzaWrapper.wrapper(stanza, 201));
            return replies;
        }
        List<Channel> toChannels= serverRuntimeContext.getProtocolChannelRegistry().get(toEntity);
        if (!serverRuntimeContext.getProtocolChannelRegistry().isOnline(toEntity)) {
            replies.addReply(fromChannel, StanzaWrapper.wrapperOffline(stanza));
        } else {
            replies.addReply(fromChannel, StanzaWrapper.wrapperOnline(stanza));
            replies.addReply(toChannels, StanzaWrapper.wrapper(stanza, body));
        }
        serverRuntimeContext.getMessagePipeline().push(toEntity, stanza);
        if(messagePersistencePipeline !=null && ConfigHolder.enableMessagePersistence()){
            messagePersistencePipeline.save(stanza.body());
        }
        return replies;
    }

    @Override
    public ModuleServiceType moduleServiceType() {
        return ModuleServiceType.chat;
    }
}
